package com.bjtu.ptsite.tracker.job;

import com.bjtu.ptsite.mapper.PeerMapper;
import com.bjtu.ptsite.tracker.client.TrackerClient;
import com.turn.ttorrent.tracker.TrackedPeer;
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@Component
@Slf4j
public class ActiveDetectionSchedule {

    @Autowired
    private TrackerClient trackerClient;

    @Autowired
    private PeerMapper peerMapper;

    /**
     * 每隔10分钟执行一次
     * //@Scheduled(cron = "0 0/10 * * * *")
     */
    public void activeDetection() {
        Tracker tracker = trackerClient.getTracker();
        for (TrackedTorrent torrent : tracker.getTrackedTorrents()) {
            Iterator<Map.Entry<String, TrackedPeer>> iterator = torrent.getPeers().entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, TrackedPeer> entry = iterator.next();
                TrackedPeer peer = entry.getValue();
                long lastAnnounceTime = getLastAnnounceTime(peer);
                if (System.currentTimeMillis() - lastAnnounceTime > 10 * 60 * 1000) {
                    iterator.remove();
                    log.info("清理了不活跃的 peers:{}", peer);
                }
            }
        }

    }

    private long getLastAnnounceTime(TrackedPeer peer) {
        try {
            //反射获取值
            Field field = TrackedPeer.class.getDeclaredField("lastAnnounceTime");
            field.setAccessible(true);
            return (long) field.get(peer);
        } catch (Exception e) {
            log.error("无法获取lastAnnounceTime字段", e);
            return 0L;
        }


    }

    /**
     * 定时清理死种
     */
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void cleanOldPeers() {
        LocalDateTime expireTime = LocalDateTime.now().minusDays(7);
        int deleted = peerMapper.deleteInactivePeers(expireTime);
        log.info("清理 {} 个超过7天未 announce 的 peer", deleted);
    }

}
